import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../util/response-util";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {TableUtil} from "../../../util/table-util";
import {API, MsgConstants} from "../../../constants/constants";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {LoginService} from "./login.service";
import {MsgResult} from "../../../models/msg-result";

declare var $;
declare var moment;
//declare var datepicker;
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit,AfterViewInit{
  @ViewChild(OneOperationComponent)operation : OneOperationComponent
  table;
  config;
  config2;

  loginLogIdArr:Array<string> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private loginService: LoginService,
    private dialogService: OneDialogService,
    private response: ResponseUtil
  ) { }

  ngOnInit() {
    this.initTime();
    //初始化面包屑导航
    this.pushPage();
    //初始化表单
    this.loadLoginLog();

  }  //end ngOnInit

  proxy = {
    "loginLogDetails": () => this.loginLogDetails(),
    "loginLogDelete": () => this.loginLogDelete()
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("系统日志", "");
    this.pageSubject.pushPage("系统日志", "登录日志查询", path);
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  loadLoginLog() {
    this.table = this.tableUtil.load("one_table_loginLog",{
      columns: [
        {checkbox: true},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "userName", title: '账户名称', align: 'left'},
        {field: "type", title: '类型', align: 'left', formatter: this.typeFormat},
        {field: "authMode", title: '认证方式', align: 'left',  formatter: this.authFormat},
        {field: "clientType", title: '登录方式', align: 'left', formatter: this.loginFormat},
        {field: "RECORD_TIME", title: '登录时间', align: 'left', sortName: "RECORD_TIME", sortable: true},
        {field: "ip", title: 'ip', align: 'left'},
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_login",
      url: API.loginLogPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.userName = $("#userName").val();
        params.startTime =  $("#startTime").val();
        params.endTime = $("#endTime").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.RECORD_TIME = value.recordTime || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      sortOrder: 'desc',
      sortName: 'RECORD_TIME',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  typeFormat(value, row, index) {
    if (value == '1') {
      return '登入';
    }
    if (value == '2') {
      return '登出';
    }
  }

  loginFormat(value, row, index) {
    if (value == '1') {
      return 'web登录';
    }
    if (value == '2') {
      return '手机app登录';
    }
  }

  authFormat(value, row, index) {
    if (value == '1') {
      return 'SESSION';
    }
    if (value == '2') {
      return 'JWT';
    }
  }
  //初始化日期插件
  initTime(){
    let timeData = moment().format("YYYY-MM-DD HH:mm:ss");
    let startDate = moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss");

    this.config = {
      timePicker:true,
      timePickerIncrement:1,
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      maxDate:moment().format("YYYY-MM-DD HH:mm:ss"),
      locale:{
        format:"YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      // startDate: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
      // startDate: moment().subtract(6,"month").format("YYYY-MM-DD HH:mm:ss"),
      startDate: moment().add(5,'m').subtract(1,"days").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().add(5,'m').format("YYYY-MM-DD HH:mm:ss")
    };
    this.config2 = {
      timePicker:true,
      timePickerIncrement:1,
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      // maxDate:timeData,
      locale:{
        format:"YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: moment().add(5,"m").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().add(5,"m").format("YYYY-MM-DD HH:mm:ss")
    };

    $("#startTime").daterangepicker(this.config);
    $("#endTime").daterangepicker(this.config2);
  }

  loginLogDetails(){
    let row = this.table.bootstrapTable('getSelections');
    this.loginLogIdArr = this.tableUtil.getIds(row);
    if(this.loginLogIdArr.length != 1){
      this.dialogService.modalInfo('请选择一条数据！');
    }else{
      this.router.navigate(['login-detail',{id:this.loginLogIdArr[0]}],{relativeTo:this.route});
    }

  }

  loginLogDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.loginLogIdArr = this.tableUtil.getIds(rows);
    if(this.loginLogIdArr.length == 0){
      this.dialogService.modalInfo('请选择一条数据！');
    }else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？',this.deleteExceptionLog);
    }
  }

  /**
   *  1.调用后台接口
   *  2.对结果进行处理
   */
  private deleteExceptionLog=()=>{
    this.loginService.loginLogDelete(this.loginLogIdArr).subscribe(
      result => this.response.success(result,this.processLoginLogResult),
      error => this.response.error(error)
    );
  }

  /**
   * 对结果进行判断并进行处理
   * @param {MsgResult} result
   */
  private processLoginLogResult =(result:MsgResult)=>{
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.dialogService.success(result.message);
      this.search();
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.error(result.message);
    }
  }


}



